/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server1;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import game.*;
import client.*;

/**
 *
 * @author timbeer
 */
public class Server extends Thread {

    ArrayList<Socket> clients = new ArrayList();
    int port;
    ServerSocket serversocket;
    Socket socket;
    private boolean ServerStatus = true;
    Spiel spiel;
    //Client client;

    public Server(int port) {
        this.port = port;
    }

    public void removeAllClients() throws IOException {

        for (Socket socket : clients) {
            socket.close();
        }
        clients.removeAll(clients);
    }

    @Override
    public void run() {
        
        if(clients.size() <=4){
                System.out.println("Anzahl verbunden Clients: " +clients.size());
            }
        else{
            setServerStatus(false);
        }
        
        try {
            serversocket = new ServerSocket(port);
            System.out.println("Server is listening on port " + port);

            
            
            while (true) {

                socket = serversocket.accept();
                

                System.out.println("Verbindung zum client hergestellt.");

                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

//                    clients.add(client, oos);
                clients.add(socket);

                new ServerThread(this, socket);

            }



        } catch (IOException ex) {
            System.out.println(ex.toString());;
        }

    }

    public void sendToAll(Spiel s) {
        // We synchronize on this because another thread might be
        // calling removeConnection() and this would screw us up
        // as we tried to walk through the list
        synchronized (clients) {

            //for each client
            for (Socket c : clients) {
                try {
                    //get the output stream
                    ObjectOutputStream oos = (ObjectOutputStream) c.getOutputStream();

                    //send the object

                    oos.writeObject(spiel);

                    System.out.println("Object sent");

                } catch (IOException ie) {
                    System.out.println(ie);
                }
            }

        }

    }
    
    public void setServerStatus(boolean b){
        this.ServerStatus = b;
    }
}
